package org.lxy.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.lxy.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author 卢心怡
 */
@Aspect
@Component
@Slf4j
public class CenterAspect extends BaseController {

    @Pointcut("execution(* org.lxy.controller.*.*(..))")
    public void aspectTarget(){};

    @Autowired
    private HttpServletRequest httpServletRequest;

    @AfterReturning(value = "aspectTarget()",returning="returnValue")
    public void After(JoinPoint joinPoint,Object returnValue){
        if (Objects.nonNull(returnValue) && returnValue instanceof ModelAndView){
            ModelAndView modelAndView = (ModelAndView) returnValue;
            Object[] args=null;
            String[] parameterNames=null;
            try {
                args = joinPoint.getArgs();
                Signature signature = joinPoint.getSignature();
                MethodSignature methodSignature = (MethodSignature) signature;
                parameterNames = methodSignature.getParameterNames();
                if (Objects.nonNull(parameterNames) && parameterNames.length>0){
                    for (int i = 0; i < parameterNames.length; i++) {
                        modelAndView.addObject(parameterNames[i], args[i]);
                    }
                }
                log.info("参数解析成功 请求url[{}] args[{}] parameterNames[{}]",Objects.nonNull(httpServletRequest)?httpServletRequest.getRequestURI():"非http请求",args,parameterNames);
            } catch (Exception e) {
                log.error("参数解析异常 args[{}] parameterNames[{}]",args,parameterNames, e);
            }
            if (!httpServletRequest.getRequestURI().contains("login")){
                modelAndView.addObject("user", getUserInfo());
                modelAndView.addObject("Account", getUserInfo());
                modelAndView.addObject("entity", getUserInfo());
            }
        }
    }
}
